class Solution:
    def loudAndRich(self, richer: list, quiet: list) -> list:
        def dfs(adj, n, minQ, memo):
            if n in memo:
                return memo[n]
            r = n
            for nex, nexQ in adj[n]:
                tempN, tempQ = dfs(adj, nex, min(minQ, nexQ), memo)
                if tempQ < minQ:
                    minQ = tempQ
                    r = tempN
            memo[n] = (r, minQ)
            return r, minQ

        adj = [[] for _ in range(len(quiet))]
        for i in range(len(richer)):
            adj[richer[i][1]] += [(richer[i][0], quiet[richer[i][0]])]
        ans = [i for i in range(len(quiet))]
        memo = {}
        for i in range(len(quiet)):
            ans[i] = dfs(adj, i, quiet[i], memo)[0]
        return ans
